<!--
 * @Author: guandeshen 295570679@qq.com
 * @Date: 2024-05-08 23:51:45
 * @LastEditors: 关德参 2257609862@qq.com
 * @LastEditTime: 2024-09-15 17:44:18
 * @FilePath: /task-admin/src/views/dashboard/index.vue
 * @Description: 
 * 
 * Copyright (c) 2024 by ${git_name_email}, All Rights Reserved. 
-->
<template>
  <div class="dashboard-container">
    <!-- 列表 -->
    <page-content
      ref="contentRef"
      :content-config="contentConfig"
      :stripe="true"
      @add-click="handleAddClick"
      @edit-click="handleEditClick"
      @view-click="handleViewClick"
    >
      <template #top-data>
        <div class="top-select mt-24px">
          <div class="select-item">
            <!-- <i class="iconfont icon-xiangmu"></i> -->
            <svg-icon icon-class="project-select" />
            <el-select
              v-model="project"
              :placeholder="$t('common.selectProject')"
              size="large"
              style="flex: 1"
              @change="handleProjectChange"
            >
              <el-option
                v-for="item in formProjectOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </div>

          <span class="line"></span>
          <div class="select-item">
            <!-- <i class="iconfont icon-gongdi"></i> -->
            <svg-icon icon-class="site-select" />
            <el-select
              v-model="site"
              :placeholder="$t('common.selectSite')"
              size="large"
              style="flex: 1"
              @change="handleSiteChange"
            >
              <el-option
                v-for="item in siteOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </div>
        </div>
      </template>
      <template #status="scope">
        <span
          class="table-status"
          :class="`status_${statusOptions[scope.row.status + 1].value}`"
          >{{ statusOptions[scope.row.status + 1].label }}</span
        >
      </template>
    </page-content>

    <el-drawer
      v-model="drawerDialog.visible"
      :title="drawerDialog.title"
      size="1260px"
      @close="handleDrawerCloseDialog"
    >
      <div class="drawer-box">
        <!-- 头部信息 -->
        <div
          class="bg-[#F2F3F5] p8 mb-4 flex justify-between"
          v-if="viewType != 0"
        >
          <ul class="flex flex-1 justify-between">
            <li class="h-56px pr-30px flex flex-col shrink-0">
              <span class="text-[#969799] text-14px font-500 lh-24px mb-8px">{{
                $t("common.projectName")
              }}</span>
              <p
                class="text-[#323233] m-0 ellipsis w-[100%] text-16px font-900 lh-24px"
              >
                {{ projectInfoForm?.p_name }}
              </p>
            </li>
            <li class="h-56px pr-30px flex flex-col shrink-0">
              <span class="text-[#969799] text-14px font-500 lh-24px mb-8px">{{
                $t("common.siteName")
              }}</span>
              <p
                class="text-[#323233] m-0 ellipsis w-[100%] text-16px font-900 lh-24px"
              >
                {{ siteInfo?.s_name }}
              </p>
            </li>
            <li class="h-56px pr-30px flex flex-col shrink-0">
              <span class="text-[#969799] text-14px font-500 lh-24px mb-8px">{{
                $t("common.WBS")
              }}</span>
              <p
                class="text-[#323233] m-0 ellipsis w-[100%] text-16px font-900 lh-24px"
              >
                {{ wbsInfoForm?.wbs_name }}
              </p>
            </li>

            <li class="h-56px pr-30px flex flex-col shrink-0">
              <span class="text-[#969799] text-14px font-500 lh-24px mb-8px">{{
                $t("common.projectLeader")
              }}</span>
              <p
                class="text-[#323233] m-0 ellipsis w-[100%] text-16px font-900 lh-24px"
              >
                {{ (taskInfoForm as any)?.person_incharge?.nickname }}
              </p>
            </li>
            <li class="h-56px pr-30px flex flex-col shrink-0">
              <span class="text-[#969799] text-14px font-500 lh-24px mb-8px">{{
                $t("common.status")
              }}</span>
              <span class="table-status" :class="`status_1`">{{
                statusOptions[
                  taskInfoForm?.status ? Number(taskInfoForm?.status) + 1 : 1
                ].label
              }}</span>
            </li>
            <li class="h-56px w-190px pr-30px flex flex-col shrink-0">
              <span class="text-[#969799] text-14px font-500 lh-24px mb-8px">{{
                $t("common.progress")
              }}</span>
              <el-progress
                :text-inside="true"
                :stroke-width="24"
                :percentage="taskInfoForm?.schedule"
              />
            </li>
          </ul>
        </div>
        <!-- tab -->
        <el-tabs
          v-model="activeName"
          class="demo-tabs"
          @tab-click="handleTabClick"
        >
          <!-- 基本信息 -->
          <el-tab-pane name="first">
            <template #label>
              <span class="custom-tabs-label">
                <svg-icon
                  class="w-14px h-14px mr-5px text-[#969799]"
                  :icon-class="
                    activeName !== 'first'
                      ? 'task-info-no-selecte'
                      : 'task-info-selecte'
                  "
                />
                {{ $t("common.taskInfo") }}
              </span>
            </template>

            <div
              class="flex h-52px px-16px py-15px border-rd-8px bg-[#F0F5FF] items-center text-[#323233] text-16px font-900"
            >
              <i class="i-ep:arrow-down w-1em h-1em mr-8px"></i
              >{{ $t("common.basicInfo") }}
            </div>
            <BasicInfoForm
              ref="basicInfoFormFormRef2"
              :disabled="viewType == 2 ? false : true"
              :projectInfo="projectInfo"
              :projectOptions="formProjectOptions"
              :groupleaderOptions="groupleaderOptions"
              :stakeholderOptions="stakeholderOptions"
              :pId="projectId"
              :sId="siteId"
              :wId="wbsId"
            />
            <div
              v-if="viewType != 0"
              class="flex h-52px px-16px py-15px border-rd-8px bg-[#F0F5FF] items-center text-[#323233] text-16px font-900"
            >
              <i class="i-ep:arrow-down w-1em h-1em mr-8px"></i
              >{{ $t("common.systemInfo") }}
            </div>
            <SystemForm v-if="viewType != 0" :systemInfo="systemInfo" />
          </el-tab-pane>
          <!-- 添加工具 -->
          <el-tab-pane name="second">
            <template #label>
              <span class="custom-tabs-label">
                <svg-icon
                  class="w-14px h-14px mr-5px text-[#969799]"
                  :icon-class="
                    activeName !== 'second'
                      ? 'addToolsNoSelect'
                      : 'addToolsSelect'
                  "
                />
                {{ $t("common.addTools") }}
              </span>
            </template>
            <!-- 列表 -->
            <AddTools
              ref="addToolsRef"
              :viewType="viewType"
              :productsData="productsData"
              :rentalData="rentalData"
              :wbsId="wbsId"
            />
          </el-tab-pane>
          <!-- 添加人员 -->
          <el-tab-pane name="third">
            <template #label>
              <span class="custom-tabs-label">
                <svg-icon
                  class="w-14px h-14px mr-5px text-[#969799]"
                  :icon-class="
                    activeName !== 'third'
                      ? 'addPersonnelNoSelect'
                      : 'addPersonnelSelect'
                  "
                />
                {{ $t("common.addPersonnel") }}
              </span>
            </template>
            <AddPersonnel
              ref="addPersonnelRef"
              :viewType="viewType"
              :userData="userData"
              :wbsId="wbsId"
            />
          </el-tab-pane>

          <!-- 损失备注 -->
          <el-tab-pane name="four">
            <template #label>
              <span class="custom-tabs-label">
                <svg-icon
                  class="w-14px h-14px mr-5px text-[#969799]"
                  :icon-class="
                    activeName !== 'four'
                      ? 'lossRemarksNoSelect'
                      : 'lossRemarksSelect'
                  "
                />
                {{ $t("common.lossRemarks") }}
              </span>
            </template>
            <LossRemarks
              ref="lossRemarksRef"
              :viewType="viewType"
              :wbsId="wbsId"
              :data="lossList"
            />
          </el-tab-pane>

          <!-- 计划 -->
          <el-tab-pane name="five" v-if="viewType == 1">
            <template #label>
              <span class="custom-tabs-label">
                <svg-icon
                  class="w-14px h-14px mr-5px text-[#969799]"
                  :icon-class="
                    activeName !== 'five' ? 'plan-no-select' : 'plan-select'
                  "
                />
                {{ $t("common.taskPlans") }}
              </span>
            </template>
            <TaskPlansC ref="taskPlansRef" :data="taskPlans" />
          </el-tab-pane>
        </el-tabs>
      </div>
      <template #footer>
        <div class="dialog-footer" v-show="viewType != 1">
          <el-button type="primary" @click="handleDrawerSubmitClick">{{
            $t("common.save")
          }}</el-button>
          <el-button @click="handleDrawerCloseDialog">{{
            $t("common.cancel")
          }}</el-button>
        </div>
      </template>
    </el-drawer>
  </div>
</template>

<script setup lang="ts">
import { reactive, ref, onMounted } from "vue";
import DashboardAPI from "@/api/dashboard";
import type PageContent from "@/components/PageContent/index.vue";
import contentConfig from "./config/content";
import { useRouter } from "vue-router";
import type { IObject } from "@/hooks/usePage";
import type { TabsPaneContext } from "element-plus";
import { WBSProjectList, ISite, WBSList } from "@/api/wbs/model";
import BasicInfoForm from "./components/BasicInfoForm/index.vue";
import AddTools from "./components/AddTools/index.vue";
import AddPersonnel from "./components/AddPersonnel/index.vue";
import TaskPlansC from "./components/TaskPlans/index.vue";
import LossRemarks from "./components/LossRemarks/index.vue";
import {
  TaskUsers,
  LeaseGoods,
  SaleGoods,
  TaskInfo,
  LossInfo,
  LossList,
  ProjectInfo,
  WbsInfo,
  InchargeObj,
  SiteInfo,
  TaskPlans,
} from "@/api/task/model";
import WBSAPI from "@/api/wbs";
import TaskAPI from "@/api/task";
import { active } from "sortablejs";
// import { ProjectList } from "@/api/dashboard/model";

defineOptions({
  name: "Dashboard",
  inheritAttrs: false,
});
const router = useRouter();
const { t } = useI18n();
// 状态-1=已取消，0=未开始，1=进行中，2=已完成
const statusOptions = ref<Options[]>([
  {
    value: -1,
    label: t("common.cancelled"),
  },
  {
    value: 0,
    label: t("common.notStarted"),
  },
  {
    value: 1,
    label: t("common.haveInHand"),
  },
  {
    value: 2,
    label: t("common.completed"),
  },
]);

const siteId = ref("");
const projectId = ref("");
const wbsId = ref("");
const taskId = ref("");
const projectInfo = ref<WBSProjectList>();

const project = ref("");
const site = ref("");

const siteOptions = ref<Options[]>([]);

const getSiteOptions = async () => {
  let params: Params = {
    page: 1,
    page_size: 10000,
  };
  if (selectValue.project_id) {
    params["project_id"] = selectValue.project_id;
  }
  const data = await DashboardAPI.getSite(params);
  if (data.list.length > 0) {
    siteOptions.value = data.list.map((item) => {
      return {
        value: item.id,
        label: item.s_name,
      };
    });
  }
};

const contentRef = ref<InstanceType<typeof PageContent>>();
interface Params {
  project_id?: number;
  site_id?: number;
  page?: number;
  page_size: number;
}
const selectValue = reactive({
  project_id: 0,
  site_id: 0,
});
const handleProjectChange = (e: number) => {
  let params: Params = {
    project_id: e,
    page_size: 10,
  };
  selectValue.project_id = e;
  selectValue.site_id = 0;
  site.value = "";
  getSiteOptions();
  contentRef.value?.fetchPageData(params, true);
};
const handleSiteChange = (e: any) => {
  let params: Params = {
    site_id: e,
    page_size: 10,
  };
  selectValue.site_id = e;
  if (selectValue.project_id) {
    params["project_id"] = selectValue.project_id;
  }
  contentRef.value?.fetchPageData(params, true);
};

// 弹窗
const drawerDialog = reactive({
  title: "",
  visible: false,
});

const activeName = ref("first");
const handleTabClick = (tab: TabsPaneContext, event: Event) => {
  console.log(tab, event);
};

/** 关闭弹窗 */
const basicInfoFormFormRef2 = ref(ElForm);
function handleDrawerCloseDialog() {
  activeName.value = "first";
  drawerDialog.visible = false;
  basicInfoFormFormRef2.value.formRef.resetFields();
  basicInfoFormFormRef2.value.formRef.clearValidate();
  basicInfoFormFormRef2.value.formData.id = undefined;
  basicInfoFormFormRef2.value.formData.status = 1;
  basicInfoFormFormRef2.value.formData.project_id = projectId.value;
  basicInfoFormFormRef2.value.formData.site_id = siteId.value;
  basicInfoFormFormRef2.value.formData.wbs_id = wbsId.value;
}

// 获取详情
const viewType = ref(0); //0:新增 1: 查看 2:编辑
const systemInfo = ref<SystemForm | undefined>();
const productsData = ref<SaleGoods[]>();
const rentalData = ref<LeaseGoods[]>();
const userData = ref<TaskUsers[]>();
const lossList = ref<LossList[]>();
const projectInfoForm = ref<ProjectInfo>();
const wbsInfoForm = ref<WbsInfo>();
const taskInfoForm = ref<TaskInfo>();
const siteInfo = ref<SiteInfo>();
const taskPlans = ref<TaskPlans[]>();

const getDetail = (row: IObject) => {
  console.log("%c Line:522 🥚 row", "color:#ed9ec7", row);
  drawerDialog.visible = true;
  drawerDialog.title = row.task_name;

  TaskAPI.detail({ task_id: row.id }).then((data) => {
    systemInfo.value = data.system_info;
    productsData.value = data.sale_goods;
    rentalData.value = data.lease_goods;
    userData.value = data.task_users;
    lossList.value = data?.loss_info?.loss_list?.map((item) => {
      return {
        ref: "666",
        ...item,
      };
    });

    projectId.value = data.project_info?.id as string;
    siteId.value = data.site_info?.id as string;
    wbsId.value = data.wbs_info?.id as string;
    taskId.value = data.task_info?.id as string;

    projectInfoForm.value = data.project_info;
    wbsInfoForm.value = data.wbs_info;
    taskInfoForm.value = data.task_info;
    siteInfo.value = data.site_info;
    taskPlans.value = data.task_plans;
    Object.assign(basicInfoFormFormRef2.value.formData, data.task_info);
    basicInfoFormFormRef2.value.formData["person_incharge"] = (
      data.task_info as any
    )?.person_incharge?.nickname;

    basicInfoFormFormRef2.value.formData["person_incharge_phone"] = (
      data.task_info as any
    )?.person_incharge?.mobile;
  });
};
// 新增
const handleAddClick = () => {
  viewType.value = 0;
  drawerDialog.visible = true;
  drawerDialog.title = t("common.addTask");

  systemInfo.value = {};
  productsData.value = [];
  rentalData.value = [];
  userData.value = [];
  lossList.value = [];
  projectInfoForm.value = {};
  wbsInfoForm.value = {};
  taskInfoForm.value = {};
  siteInfo.value = {};
  taskPlans.value = [];
};
// 查看
const handleViewClick = (row: IObject) => {
  taskId.value = row.id;
  viewType.value = 1;
  getDetail(row);
};

// 编辑
const handleEditClick = (row: IObject) => {
  taskId.value = row.id;
  viewType.value = 2;
  getDetail(row);
};

// 编辑保存
const addPersonnelRef = ref(ElForm);
const addToolsRef = ref(ElForm);
const lossRemarksRef = ref(ElForm);
const handleDrawerSubmitClick = () => {
  basicInfoFormFormRef2.value.formRef.validate((valid: any) => {
    const sale_goods = addToolsRef.value.newProductsData;
    const lease_goods = addToolsRef.value.newRentalData;
    const task_users = addPersonnelRef.value.newUserData;
    const loss_list = lossRemarksRef.value.newData;
    if (
      (sale_goods.length > 0 &&
        sale_goods.some((item: any) => item.asset_id === "")) ||
      (lease_goods.length > 0 &&
        lease_goods.some((item: any) => item.asset_id === "")) ||
      (task_users.length > 0 &&
        task_users.some((item: any) => item.user_ref === "")) ||
      (loss_list.length > 0 &&
        loss_list.some((item: any) => item.remark === "" || item.amount === ""))
    ) {
      ElMessage.error(t("common.pleaseFillFirst"));
      return;
    }
    if (valid) {
      const Id = basicInfoFormFormRef2.value.formData.id;
      TaskAPI.add({
        task_info: basicInfoFormFormRef2.value.formData,
        sale_goods: sale_goods.map((item: any) => {
          return {
            id: item.id == "-1" ? undefined : item.id,
            asset_id: item.asset_id,
            unit_price: item.unit_price,
            num: item.num,
          };
        }),
        lease_goods: lease_goods.map((item: any) => {
          return {
            id: item.id == "-1" ? undefined : item.id,
            asset_id: item.asset_id,
            unit_price: item.unit_price,
            num: item.num,
            days: item.days,
          };
        }),
        task_users: task_users.map((item: any) => {
          return {
            id: item.id == "-1" ? undefined : item.id,
            user_id: item.user_ref,
            daily_wage: item.daily_wage,
            days: item.days,
          };
        }),
        loss_list: loss_list.map((item: any) => {
          return {
            id: item.id == "-1" ? undefined : item.id,
            amount: item.amount,
            remark: item.remark,
          };
        }),
      })
        .then(() => {
          ElMessage.success(
            Id
              ? t("common.modifiedSuccessfully")
              : t("common.newSuccessfullyAdded")
          );
          handleDrawerCloseDialog();
          contentRef.value?.fetchPageData({}, true); //重置查询
        })
        .finally(() => {
          // loading.value = false
        });
    } else {
      activeName.value = "first";
      ElMessage.error(t("common.completeInfo"));
    }
  });
};

// 获取项目和工地和wbs列表
const formProjectOptions = ref<Options[]>([]);
const groupleaderOptions = ref<Options[]>([]);
const stakeholderOptions = ref<Options[]>([]);
const getProjectOptions = async () => {
  const data = await DashboardAPI.getProject({
    page: 1,
    page_size: 10000,
  });
  if (data.list.length > 0) {
    formProjectOptions.value = data.list.map((item) => {
      return {
        value: item.id,
        label: item.p_name,
      };
    });
  }
};

const getGroupleader = async () => {
  const data = await TaskAPI.getGroupleader({
    page: 1,
    page_size: 10000,
  });
  if (data.list.length > 0) {
    groupleaderOptions.value = data.list.map((item) => {
      return {
        value: item.id,
        label: item.nickname,
      };
    });
  }
};

const getStakeholder = async () => {
  const data = await TaskAPI.getStakeholder({
    page: 1,
    page_size: 10000,
  });
  if (data.list.length > 0) {
    stakeholderOptions.value = data.list.map((item) => {
      return {
        value: item.id,
        label: `${item.first_n} ${item.last_n}`,
      };
    });
  }
};

onMounted(() => {
  getProjectOptions();
  getGroupleader();
  getStakeholder();
});
</script>

<style lang="scss" scoped>
.dashboard-container {
  position: relative;
  padding: 16px 24px;

  .top-select {
    box-sizing: border-box;
    display: flex;
    align-items: center;
    justify-content: space-between;
    height: 68px;
    padding: 16px 0;
    margin-bottom: 24px;
    background: #fff;
    border-radius: 4px;

    span {
      &.line {
        display: block;
        width: 1px;
        height: 36px;
        background-color: #f3f3f3;
      }
    }

    .select-item {
      display: flex;
      flex: 1;
      align-items: center;
      padding: 0 24px;

      .svg-icon {
        width: 22px !important;
        height: 22px !important;
      }
    }

    :deep(.el-select__wrapper) {
      box-shadow: none;

      &.is-hovering:not(.is-focused) {
        box-shadow: none;
      }
    }
  }
}
</style>
